package com.hxzy.security;

import com.hxzy.common.exception.ServerException;
import com.hxzy.common.vo.CodeEnum;
import com.hxzy.entity.system.SysUser;
import com.hxzy.service.system.SysRoleService;
import com.hxzy.service.system.SysUserService;
import com.hxzy.vo.system.HxzyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * spring security，通过自定义数据库访问接口实现
 */
@Service
public class TZXMUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 验证用户名
        SysUser sysUser = this.sysUserService.loadUserByUsername(username);
        if(Objects.isNull(sysUser)){
            throw new ServerException(CodeEnum.ADMIN_ACCOUNT_NOT_FOUND);
        }

        //用户是否被锁定
        if(sysUser.getStatus().equalsIgnoreCase("1")){
            throw new ServerException(CodeEnum.ADMIN_ACCOUNT_LOCKED);
        }

        //用户-->角色
        Set<String> ownRoleKey = this.sysRoleService.getOwnRoleKey(sysUser.getId());
        //用户--》 角色--》菜单权限
        Set<String> ownPerms =new HashSet<>();
        // 超级管理员
        if(ownRoleKey.contains("admin")){
            ownPerms.add("*:*:*");
        }else{
            //不是超级管理员
            ownPerms=this.sysRoleService.getOwnRoleMenuPerms(sysUser.getId());
        }

        //加载菜单权限
        HxzyUser  hxzyUser=new HxzyUser();
        hxzyUser.setSysUser(sysUser);
        //角色权限
        hxzyUser.setRoles(ownRoleKey);
        //菜单权限
        hxzyUser.setPermission(ownPerms);
        return hxzyUser;
    }
}
